package com.lvyq.javaprint.util;

import cn.hutool.json.JSONUtil;
import com.lvyq.javaprint.common.GlobalCode;
import com.lvyq.javaprint.ws.WebSocketServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lvyq  文件转换
 * @version 1.0
 * Create by 2025-06-13 16:23
 */
public class ImgPrintUtils {


    /**
     * @description 路径转换
     * @author lvyq
     * @param[1] file
     * @throws
     * @return FileInputStream
     * @time 2025-06-13 16:29
     */
    public static final FileInputStream getFileInputStream(File file,String sessionId){
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            return fileInputStream;
        } catch (FileNotFoundException e) {
            WebSocketServer.SendMessageById(JSONUtil.toJsonStr(GlobalCode.FILE_EXP),sessionId);
            throw new RuntimeException("获取文件异常:"+e.getMessage());
        }
    }

    public static InputStream getFileInputStream(MultipartFile multipartFile, String sessionId) {

        try {
            InputStream inputStream = multipartFile.getInputStream();
            return inputStream;
        } catch (IOException e) {
            WebSocketServer.SendMessageById(JSONUtil.toJsonStr(GlobalCode.FILE_EXP),sessionId);
            throw new RuntimeException("获取文件异常:"+e.getMessage());
        }
    }

    public static InputStream getFileInputStream(URL url, String sessionId) {

        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            // 5秒连接超时
            connection.setConnectTimeout(5000);
            // 10秒读取超时
            connection.setReadTimeout(10000);
            return connection.getInputStream();
        } catch (IOException e) {
            WebSocketServer.SendMessageById(JSONUtil.toJsonStr(GlobalCode.FILE_EXP),sessionId);
            throw new RuntimeException("获取文件异常:"+e.getMessage());
        }
    }
}
